package com.yexs.controller.wechat;

import com.yexs.wechat.pojo.SNSUserInfo;
import com.yexs.wechat.pojo.WeixinOauth2Token;
import com.yexs.wechat.service.WechatCoreService;
import com.yexs.wechat.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@Api("微信公众号测试API")
@RestController
@RequestMapping("/wechat")
public class WechatController {
    private static Logger log = LoggerFactory.getLogger(WechatController.class);

    @PostConstruct
    public void init() {
        // 未配置appid、appsecret时给出提示
        if ("".equals(Constant.appID) || "".equals(Constant.appSecret)) {
            log.error("appid and appsecret configuration error, please check carefully.");
        } else {
            log.info("weixin api appid:{}", Constant.appID);
            log.info("weixin api appsecret:{}", Constant.appSecret);
            // 启动定时获取access_token的线程
            new Thread(new TokenThread()).start();
        }
    }

    /**
     * 确认消息来自微信服务器
     *
     * @param request
     * @return
     */
    @ApiOperation("确认消息来自微信服务器")
    @GetMapping(value = "")
    String check(HttpServletRequest request) {

        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature2(signature, timestamp, nonce)) {
            System.out.print("微信公众测试账号回调-success========echostr=" + echostr);
            return echostr;
        } else {
            return "fail";
        }
    }

    /**
     * 处理微信服务器发来的消息
     *
     * @return
     */
    @ApiOperation("处理微信服务器发来的消息")
    @PostMapping(value = "")
    public String dealWechatRequest(HttpServletRequest request) throws UnsupportedEncodingException {
        System.out.println("----开始接受请求并处理--------------");
        // 消息的接收、处理、响应
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        // 调用核心业务类接收消息、处理消息
        String respXml = WechatCoreService.processRequest(request);
        return respXml;
    }

    /**
     * 使用@RestController时，则使用ModelAndView显示页面
     *
     * @param code
     * @return
     */
    @ApiOperation("用户网页授权后，获取用户信息")
    @GetMapping(value = "/getUserAuthInfo")
    public ModelAndView getUserAuthInfo(@RequestParam("code") String code, ModelMap map, HttpServletRequest request) {
        String view = "index";
        map.put("name", "yeShengsheng");
        map.put("wxConfig", WeixinUtil.getWxConfig(request));
        // 用户同意授权
        if (!"authdeny".equals(code)) {
            // 获取网页授权access_token
            WeixinOauth2Token weixinOauth2Token = CommonUtil.getOauth2AccessToken(code);
            // 网页授权接口访问凭证
            String accessToken = weixinOauth2Token.getAccessToken();
            // 用户标识
            String openId = weixinOauth2Token.getOpenId();
            // 获取用户信息
            SNSUserInfo snsUserInfo = CommonUtil.getSNSUserInfo(accessToken, openId);
            log.info(snsUserInfo.getCity());
            map.put("snsUserInfo", snsUserInfo);

        } else {
            view = "login";
        }
        ModelAndView mv = new ModelAndView(view);
        return mv;
    }

    @ApiOperation("测试 集成jsp后，是否可以返回视图而不是json")
    @GetMapping(value = "/testjsp")
    public ModelAndView testjsp(ModelMap modelMap) {
        ModelAndView mv = new ModelAndView("login");
        modelMap.put("name", "shengshengYe");
        return mv;
    }
}
